<?php

namespace App\Http\Controllers;

use App\Models\Friend;
use App\Models\WxUser;
use App\Services\FriendChatService;
use App\Services\IMServices;
use App\Tools\JsonTools;
use App\Tools\RedisTools;
use Illuminate\Http\Request;

class FriendController extends Controller
{
    //
    /**
     * 好友列表
     * @param Request $request
     * @return array
     */
    public function friendList(Request $request){
        $id = $request->id;
        $friend = Friend::where('uid',$id)->get();
        if (!$friend){
            return JsonTools::JsonError([],2020,'你还没有好友快点添加吧');
        }
        $data = [];
        foreach ($friend as $v){
            $myfriend = WxUser::where('id',$v['friend_id'])->first();
            if ($myfriend){
                $data[] = [
                    'id'=>$myfriend['id'],
                    'nickname'=>$myfriend['user_name'],
                    'user_image'=>$myfriend['user_image']
                ];
            }

        }

        return JsonTools::JsonSuccess($data,200,'好友列表');

    }

    /**
     * IM单人聊天
     * @param Request $request
     * @return array
     */

    public function sendFriend(Request $request){

        $data= $request->all();
        $id = $request->id;

        $res = FriendChatService::friendChat($data,$id);

        if ($res){
            return JsonTools::JsonSuccess($res,200,'消息发送成功');
        }else {
            return JsonTools::JsonError([],2021,'消息发送失败');
        }
    }

    /**
     * 获取聊天记录
     * @param Request $request
     * @return array
     */

    public function searchMessage(Request $request){

        $id = $request->id;

        $friend = $request->input('friend');

        $redis = RedisTools::getInstance()->connectRedis();

        $message = $redis->get('message'.$friend.$id);

        if ($message){
            return JsonTools::JsonSuccess(json_decode($message,true),200,'历史消息');
        }
        $res = FriendChatService::getMessage($friend,$id);

        if ($res){
            return JsonTools::JsonSuccess($res,200,'历史消息');
        }else {
            return JsonTools::JsonError([],2021,'获取消息失败');
        }
    }

    /**
     * 获取好友和自己的IM账号
     * @param Request $request
     */

    public function userIM(Request $request){

        $id = $request->id;

        $friend = $request->input('friend');

        $res = FriendChatService::userMessage($friend,$id);

        if ($res){
            return JsonTools::JsonSuccess($res,200,'用户与好友信息');
        }
    }
}
